package com.wn.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wn.common.PageParam;
import com.wn.mapper.*;
import com.wn.ov.*;
import com.wn.pojo.*;
import com.wn.resopnse.ResponseCode;
import com.wn.resopnse.ServerResponse;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @BelongsProject: his
 * @BelongsPackage: com.wn.service
 * @Author: faker
 * @CreateTime: 2020-10-26 14:37
 * @Description: 护士所使用的子模块
 */
@Service
@Transactional
public class NurseService {

    @Autowired
    private PatientDetailMapper patientDetailMapper;

    @Autowired
    private HospitalizedApplicationMapper hospitalizedApplicationMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private MedicalAdviceMapper medicalAdviceMapper;

    @Autowired
    private CostMapper costMapper;

    @Autowired
    private DepartmentCodeMapper departmentCodeMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    //获取护士列表
    public ServerResponse getNurseList(){
        //获取护士列表
        List<User> nurseList = userService.getNurseList();
        return new ServerResponse(ResponseCode.SUCCESS,nurseList);
    }

    //条件查询患者列表（在院或出院）
    public ServerResponse queryPatientByStatus(PageParam<PatientOv> pageParam){
        if(!StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())){
            //高级检索
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for(int i=0;i<pageParam.getOrderParams().length;i++){
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }

            List<PatientOv> patientOvList = patientDetailMapper.fuckSuperSearch(pageParam.getSuperSearchKeyWord());
            PageInfo<PatientOv> patientOvPageInfo = new PageInfo<>(patientOvList);
            return new ServerResponse(ResponseCode.SUCCESS,patientOvPageInfo);
        }

        //分页
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        //排序
        for(int i=0;i<pageParam.getOrderParams().length;i++){
            PageHelper.orderBy(pageParam.getOrderParams()[i]);
        }

        List<PatientOv> patientOvList = patientDetailMapper.getPatientListByCondition(pageParam.getModel());
        PageInfo<PatientOv> patientOvPageInfo = new PageInfo<>(patientOvList);
        return new ServerResponse(ResponseCode.SUCCESS,patientOvPageInfo);
    }

    //入院登记（通过审核并修改患者详情）
    public ServerResponse addPatientDetail(HospitalizedApplication hospitalizedApplication,Integer userId){
        //修改该患者在入院申请单上的住院状态
        hospitalizedApplication.setStatus(1);
        int result = hospitalizedApplicationMapper.updateByPrimaryKeySelective(hospitalizedApplication);
        if(result > 0){
            //修改成功，修改患者详情表
            PatientDetail patientDetail = new PatientDetail();
            patientDetail.setPatientId(hospitalizedApplication.getPatientId());
            patientDetail.setStatus(hospitalizedApplication.getStatus());
            patientDetail.setUpdateUserId(userId);

            //调用方法修改患者详情数据
            int i = patientDetailMapper.updateStatusByPatientId(patientDetail);
            if(i > 0){
                return new ServerResponse(ResponseCode.SUCCESS,"操作成功");
            }
            return new ServerResponse(ResponseCode.NO_MANAGER,"审核成功，但是患者详情表修改失败！");
        }
        //修改失败
        return new ServerResponse(ResponseCode.ERROR,"审核失败");
    }

    //查询所有的出入院申请单
    public ServerResponse getListInHospital(PageParam<HospitalizedApplication> pageParam){

        if(!StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())){
            //执行高级检索
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for(int i=0;i<pageParam.getOrderParams().length;i++){
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }

            List<HospitalizedApplicationOv> list = hospitalizedApplicationMapper.superSearch(pageParam.getSuperSearchKeyWord());
            //时间显示格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH时mm分");
            for (HospitalizedApplicationOv n:list) {
                String timeString = formatter.format(n.getTime());
                n.setTimeString(timeString);
            }
            PageInfo<HospitalizedApplicationOv> haPageInfo = new PageInfo<HospitalizedApplicationOv>(list);
            return new ServerResponse(ResponseCode.SUCCESS,haPageInfo);

        }else{
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for(int i=0;i<pageParam.getOrderParams().length;i++){
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }

            List<HospitalizedApplicationOv> list = hospitalizedApplicationMapper.getInListByStatus(pageParam.getModel());
            //时间显示格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH时mm分");
            for (HospitalizedApplicationOv n:list) {
                String timeString = formatter.format(n.getTime());
                n.setTimeString(timeString);
            }
            PageInfo<HospitalizedApplicationOv> haPageInfo = new PageInfo<HospitalizedApplicationOv>(list);
            return new ServerResponse(ResponseCode.SUCCESS,haPageInfo);
        }
    }

    //为入院的患者分配护士与床位
    public ServerResponse giveBedAndNurse(PatientDetail patientDetail,Integer userId){
        Integer id = patientDetailMapper.getPatientDetailId(patientDetail.getPatientId());
        patientDetail.setId(id);
        patientDetail.setUpdateUserId(userId);
        //修改患者详情表的数据
        int result = patientDetailMapper.updateByPrimaryKeySelective(patientDetail);
        if(result > 0){
            //修改成功，将该床位设置为占用
            Room room = new Room();
            room.setId(patientDetail.getRoomId());
            room.setIsUsed(1);
            roomService.updateIsUsedByRoomId(room);
            return new ServerResponse(ResponseCode.SUCCESS,"分配成功");
        }
        //修改失败
        return new ServerResponse(ResponseCode.ERROR,"分配失败");
    }

    //通过护士id获取其住院患者详情列表
    public ServerResponse getPatientList(Integer id){
        List<PatientDetail> patientList = patientDetailMapper.getByNurseId(id);

        return new ServerResponse(ResponseCode.SUCCESS,patientList,"查询患者列表成功");
    }

    //出院审核
    public ServerResponse updateOutHospitalStatus(HospitalizedApplication hospitalizedApplication,Integer id){
        //通过患者id查询患者的详情
        PatientDetail pp = patientDetailMapper.selectByPatientId(hospitalizedApplication.getPatientId());
        //修改申请表状态
        hospitalizedApplication.setStatus(3);
        int result = hospitalizedApplicationMapper.updateByPrimaryKeySelective(hospitalizedApplication);
        if(result > 0){
            //审核通过，修改患者详情状态
            //修改成功，修改患者详情表
            PatientDetail patientDetail = new PatientDetail();
            patientDetail.setPatientId(hospitalizedApplication.getPatientId());
            patientDetail.setStatus(2);
            patientDetail.setUpdateUserId(id);

            //调用方法修改患者详情数据
            int i = patientDetailMapper.outHospitalByPatientId(patientDetail);
            //调用方法修改床位为可用
            Room room = new Room();
            room.setId(pp.getRoomId());
            room.setIsUsed(0);
            Integer res = roomService.updateIsUsedByRoomId(room);
            if(i > 0 && res > 0){
                return new ServerResponse(ResponseCode.SUCCESS,"审核通过");
            }
            return new ServerResponse(ResponseCode.NO_MANAGER,"审核成功，但是患者详情表修改失败！");
        }
        //操作失败
        return new ServerResponse(ResponseCode.ERROR,"审核失败");
    }

    //根据病床id查询该病床的病人详细资料
    public ServerResponse lookPatientByRoomId(Integer roomId){
        //根据病房id查询病人详情
        PatientDetail patientDetail = patientDetailMapper.lookByRoomId(roomId);
        if(StringUtils.isEmpty(patientDetail)){
            //查询失败
            return new ServerResponse(ResponseCode.ERROR,"查询失败");
        }
        //查询成功
        return new ServerResponse(ResponseCode.SUCCESS,patientDetail,"查询成功");
    }

    //获取待床患者列表
    public ServerResponse getNoBedPatientList(){
        List<PatientDetail> noBedPatientList = patientDetailMapper.getNoBedPatientList();
        return new ServerResponse(ResponseCode.SUCCESS,noBedPatientList);
    }

    //获取某患者的所有医嘱
    public ServerResponse getMedicalAdviceByPatientId(PageParam<PatientDetail> pageParam){
        //分页
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        //排序
        for(int i=0;i<pageParam.getOrderParams().length;i++){
            PageHelper.orderBy(pageParam.getOrderParams()[i]);
        }

        List<MedicalAdviceOv> medicalAdviceList = medicalAdviceMapper.superSearch("", pageParam.getId());
        //时间显示格式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH时mm分");
        User uu = userService.getUserById(pageParam.getId());
        for (MedicalAdviceOv m:medicalAdviceList) {
            m.setPatientId(pageParam.getId());
            m.setPatientName(uu.getRealName());
            String timeString = formatter.format(m.getUpdateTime());
            m.setTimeString(timeString);
        }
        PageInfo<MedicalAdviceOv> pageInfo = new PageInfo<>(medicalAdviceList);
        return new ServerResponse(ResponseCode.SUCCESS,pageInfo,"成功！");
    }


    //查询患者的总费用
    public ServerResponse getAllCost(Integer id){
        CostOv costOv = costMapper.getAllCostByPatientId(id);
        return new ServerResponse(ResponseCode.SUCCESS,costOv,"查询成功");
    }

    //添加申请转科记录
    public ServerResponse addDepartmentRecord(DepartmentCode departmentCode){
        //添加申请之前先看看是否有未审核的转科申请
        List<DepartmentCode> departmentCodes = departmentCodeMapper.getNoIntoByPatientId(departmentCode.getPatientId());
        if(departmentCodes.size() > 0){
            //有，所有不能再继续申请
            return new ServerResponse(ResponseCode.SUCCESS,"不");
        }else{
            //可以添加
            int result = departmentCodeMapper.insertSelective(departmentCode);
            if(result > 0){
                //申请成功，修改患者相关记录(医生操作)
                return new ServerResponse(ResponseCode.SUCCESS,"申请成功！");
            }
            //申请失败
            return new ServerResponse(ResponseCode.ERROR,"申请失败！");
        }
    }

    //查看转科记录(通过患者id)
    public ServerResponse getDepartmentRecord(PageParam<DepartmentRecordOv> pageParam){
        //分页
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        //排序
        for(int i=0;i<pageParam.getOrderParams().length;i++){
            PageHelper.orderBy(pageParam.getOrderParams()[i]);
        }

        List<DepartmentRecordOv> departmentRecordOvs = departmentCodeMapper.getAllDepartmentRecordByPatientId(pageParam.getId());
        //时间显示格式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH时mm分");
        for (DepartmentRecordOv d:departmentRecordOvs) {
            String timeString = formatter.format(d.getCreateTime());
            d.setApplicantTime(timeString);
            String timeString2 = formatter.format(d.getUpdateTime());
            d.setAgreeTime(timeString2);
        }

        PageInfo<DepartmentRecordOv> departmentRecordOvPageInfo = new PageInfo<>(departmentRecordOvs);
        return new ServerResponse(ResponseCode.SUCCESS,departmentRecordOvPageInfo);
    }

    //驳回出入院请求
    public ServerResponse rollbackReq(HospitalizedApplication hospitalizedApplication){
        if(hospitalizedApplication.getStatus() == 0){
            //驳回入院申请，状态改为4
            hospitalizedApplication.setStatus(4);
            int result = hospitalizedApplicationMapper.updateByPrimaryKeySelective(hospitalizedApplication);
            if(result > 0){
                //驳回成功
                return new ServerResponse(ResponseCode.SUCCESS,"驳回入院申请成功");
            }else{
                //驳回失败
                return  new ServerResponse(ResponseCode.ERROR,"驳回入院申请失败");
            }
        }else if(hospitalizedApplication.getStatus() == 2){
            //驳回出院申请，状态改为1
            hospitalizedApplication.setStatus(1);
            int result = hospitalizedApplicationMapper.updateByPrimaryKeySelective(hospitalizedApplication);
            if(result > 0){
                //驳回成功
                return new ServerResponse(ResponseCode.SUCCESS,"驳回出院申请成功");
            }
            //驳回失败
            return  new ServerResponse(ResponseCode.ERROR,"驳回出院申请失败");
        }else{
            //错误
            return new ServerResponse(ResponseCode.ERROR,"状态有误");
        }
    }

    //获取科室分类（分页）
    public ServerResponse getDepartmentList(PageParam<Department> pageParam){
        //分页
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
//        //排序
//        for(int i=0;i<pageParam.getOrderParams().length;i++){
//            PageHelper.orderBy(pageParam.getOrderParams()[i]);
//        }

        List<Department> list = departmentMapper.queryList();
        PageInfo<Department> pageInfo = new PageInfo<>(list);
        return new ServerResponse(ResponseCode.SUCCESS,pageInfo,"成功");
    }

    //获取病房列表（不分页）
    public ServerResponse getRoomListByBox(Integer id){
        RoomOv roomOv = new RoomOv();
        roomOv.setDepartmentId(id);
        //调用方法
        List<RoomOv> list = roomService.getRoomListByBox(roomOv);
        return new ServerResponse(ResponseCode.SUCCESS,list);
    }

}
